<template>
    <div class="detail">
        <el-form :model="project" ref="projectForm" label-width="80px" :inline="true">
            <el-form-item label="项目名称" prop="name">
                <el-input v-model="project.name" readonly></el-input>
            </el-form-item>
            <el-form-item label="项目描述" prop="description">
                <el-input v-model="project.description" readonly></el-input>
            </el-form-item>
            <el-form-item label="项目路径" prop="path" style="width:84%">
                <el-input v-model="project.path" readonly></el-input>
            </el-form-item>
        </el-form>
        <div class="pro-content" :style="{ height: 'calc(100% - ' + projectForm?.$el.offsetHeight + 'px)' }">
            <div class="list">
                <!-- 命令列表 -->
                <!-- <h4>命令列表</h4>
                <el-table :data="commands" stripe max-height="280px">
                    <el-table-column label="名称" prop="name" width="160px" align="center" />
                    <el-table-column label="命令" prop="command" min-width="200px" />
                    <el-table-column label="操作" width="100px" fixed="right">
                        <template #default="{ row }">
                            <el-link type="primary" @click="runCommand(row.command)">运行</el-link>
                        </template>
</el-table-column>
</el-table> -->
                <!-- 插件列表 -->
                <div class="plugin-title">
                    <h4>插件列表</h4>
                    <el-button type="primary" @click="installPlugins" :disabled="!selected.length">安装选中插件</el-button>
                </div>
                <el-table :data="plugins" :style="{ maxHeight: 'calc(100% - 62px)' }" stripe
                    @selection-change="(val: PluginType[]) => { selected = val }">
                    <el-table-column type="selection" width="30" />
                    <el-table-column label="名称" prop="name" width="160px" />
                    <el-table-column label="命令" prop="command" min-width="200px" />
                </el-table>
            </div>
            <div class="shell" ref="shell-el">
                <p v-for="(item, index) in shellObj" :key="index" :class="item.type">{{ item.value }}</p>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import database from '@/api/database'
import { exec } from '@/composables/useHome'
import { ElMessage } from 'element-plus'

const route = useRoute()
const project = ref<Project>({ name: '', description: '', category_id: 0, path: '' })
const plugins = ref<PluginType[]>([])
const commands = ref<Command[]>([])
const shellEl = useTemplateRef('shell-el')
const child = ref()
const selected = ref<PluginType[]>([])
const shellObj = ref<{ type: "error" | "info", value: string }[]>([])
const projectForm = useTemplateRef('projectForm')

async function installPlugins() {
    if (selected.value.length === 0) {
        ElMessage.error('请选择要安装的插件')
        return
    }
    let next = false
    for (const select of selected.value) {
        next = false
        shellObj.value.push({ type: "info", value: `----- 正在安装插件 ${select.name} -----` })
        await exec(select.command, project.value.path, shellObj.value, () => {
            shellObj.value.push({ type: "info", value: `----- 安装完成 -----` })
            next = true
        })
        while (!next) {
            await sleep(1000)
        }
    }
}
// async function runCommand(command: string) {
//     const res = await exec(command, project.value.path, shell)
//     child.value = res
// }

async function sleep(time: number = 1000) {
    await new Promise(resolve => setTimeout(resolve, time))
}

onMounted(async () => {
    (await database()).table('projects').find<Project>(parseInt(<string>route.params.id)).then(async res => {
        if (!res) {
            ElMessage.error('项目不存在')
            return
        }

        project.value = res;
        (await database()).table('plugins').where('category_id', res.category_id).get<PluginType>().then(res => {
            plugins.value = res
        });
        (await database()).table('commands').where('category_id', res.category_id).get<Command>().then(res => {
            commands.value = res
        })
    })
})
watch(shellObj.value, async () => {
    // 超过1024行清空
    if (shellObj.value.length > 1024) {
        shellObj.value = []
    }
    if (shellEl.value) {
        await sleep(100)
        shellEl.value.scroll({
            top: shellEl.value.scrollHeight,
            behavior: 'smooth'
        })
    }
})

onUnmounted(() => {
    // 退出时关闭shell
    if (child.value) {
        child.value.kill()
    }
})
</script>

<style lang="scss" scoped>
.detail {
    height: calc(100% - 41px);
    min-width: 800px;
    overflow-x: auto;

    .pro-content {
        display: flex;
        gap: 10px;

        .list {
            flex: 0 0 300px;

            .plugin-title {
                display: flex;
                gap: 20px;
                align-items: center;
                margin: 15px 0;
            }
        }

        .shell {
            flex: 1 0 420px;
            padding: 10px;
            border-radius: 6px;
            border: 1px solid var(--el-border-color);
            background: #000;
            color: #fff;
            font-size: 12px;
            line-height: 1.8;
            height: auto;
            overflow-y: auto;
            word-break: break-all;
            text-wrap: wrap;

            .error {
                color: var(--el-color-danger);
            }
        }
    }
}
</style>